<template>
  <div class="diagnose_time_line__">
    <!--时间线-->
    <div class="time_line">
      <div class="time_line_history">
        <div class="tl-timeline">
          <div v-for="item in recordList" :key="item.id" class="tl-container right">
            <div class="date">{{ item.id }}</div>
            <div class="content">
              <h2>
                {{ item.createDate }}
                <span :style="{ color: getRecordColor(item.diagnoseType), margin: '0 0 0 5px' }">
                  {{ item.diagnoseType | fitReviewOptions }}
                </span>
              </h2>
              <div class="time_line_body">
                <el-link
                  v-if="item.diagnoseType == 100"
                  type="success"
                  style="margin-left: 5px"
                  @click.stop.native="handleOpenFile(item.context)">
                  点击查看
                </el-link>
                <div v-else>
                  {{ item.context }}
                </div>
                <div class="recorder__">{{ item.coachName }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="time_line_new">
        <div class="bottom_add">
          <div>
            <span style="margin-right: 10px">复盘主题</span>
            <el-select v-model="form.diagnoseType" placeholder="请选择复盘主题" size="small" style="width: 180px">
              <el-option
                v-for="item in ReviewOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"></el-option>
            </el-select>
          </div>
          <el-upload
            v-if="form.diagnoseType == 100"
            action="/"
            :before-upload="handleFileBeforeUpload"
            :on-progress="handleFileUploading"
            :on-success="handleFileUploadOk"
            :on-error="handleFileUploadError"
            :http-request="handleFileUpload"
            :file-list="quanFileList"
            :auto-upload="true"
            :multiple="false"
            :disabled="quanOpt.proposalUploading"
            accept=".txt,.pdf">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传 pdf/txt 文件, 且不超过20M</div>
          </el-upload>
          <div v-else style="width: 100%; text-align: center">
            <el-input
              v-model="form.context"
              size="small"
              type="textarea"
              maxlength="1000"
              show-word-limit
              clearable
              :autosize="{ minRows: 4, maxRows: 8 }"
              placeholder="请输入复盘内容"
              style="width: 100%"></el-input>
            <div>
              <el-button
                v-if="isUpdating"
                type="primary"
                size="small"
                disabled
                icon="el-icon-loading"
                style="width: 120px">
                提交中
              </el-button>
              <el-button v-else type="primary" size="small" style="width: 120px" @click.stop="handleSubmitForm">
                保存
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { fileTimelineDiagnose, geTimelineDiagnose, saveTimelineDiagnose } from '@/api/diagnose';
// 引入自定义组件
import '@/assets/css/timeline2.css';
// 引入第三方组件
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

const ReviewOptions = [
  { code: '5', name: '人力' },
  { code: '6', name: '客户运营' },
  { code: '7', name: '产品' },
  { code: '8', name: '制度' },
  { code: '9', name: '成本' },
  { code: '10', name: '新客' },
  { code: '11', name: '合规性' },
  { code: '100', name: '文件' },
];

const EmptyTimeline = {
  id: undefined,
  salonId: null,
  salonNo: null,
  salonName: '',
  diagnoseType: undefined,
  context: '',
  coachId: null,
  coachName: null,
  createDate: null,
};

export default {
  name: 'DiagTimeline',
  filters: {
    fitReviewOptions(val) {
      const tmp = ReviewOptions.find(x => x.code == val);
      if (tmp) {
        return tmp.name;
      }
      return '';
    },
  },
  data() {
    return {
      salon: {},
      recordList: [],
      ReviewOptions: ReviewOptions,
      form: EmptyTimeline,
      isUpdating: false,
      isFetching: false,
      quanFileList: [],
      quanOpt: {
        // 创建全案区域
        proposalUploading: false,
      },
    };
  },
  computed: {
    ...mapGetters(['deptId', 'openId', 'id', 'name']),
  },
  methods: {
    getRecordColor(val) {
      switch (val) {
        case 5:
        case 6:
          return '#FF7510';
        case 7:
          return '#EFAC00';
        case 8:
          return '#00A61B';
        case 9:
          return '#1073FF';
        case 10:
        case 11:
          return '#2E1BFF';
      }
    },
    handleOpenFile: async function (name) {
      if (!name || !this.salon.salonId) {
        return;
      }
      // pdf 或者 txt
      const openUrl = `/pub/diagnose/timeline?relativePath=${name}&sid=${this.salon.salonId}`;
      window.open(openUrl, '_blank');
    },
    handleFileBeforeUpload(file) {
      const allowFileTypes = ['txt', 'pdf'];
      const fileType = file.name.split('.').pop().toLowerCase();
      if (allowFileTypes.indexOf(fileType) === -1) {
        MessageBox.alert('只能上传指定格式的文件!');
        return false;
      }
      if (file.size > 1024 * 1024 * 20) {
        MessageBox.alert('文件过大!');
        return false;
      }
      return true;
    },
    handleFileUploading(event, file, fileList) {
      this.quanOpt.proposalUploading = true;
    },
    handleFileUploadOk(res, file, fileList) {
      this.quanOpt.proposalUploading = false;
    },
    handleFileUploadError(err, file, fileList) {
      this.quanOpt.proposalUploading = false;
    },
    handleFileUpload: async function (options) {
      const file = options.file;
      const formData = new FormData();
      formData.append('file', file);
      const row = {};
      row.salonId = this.salon.salonId;
      row.salonNo = this.salon.salonNo;
      row.salonName = this.salon.salonName;
      if (!row.salonId || !row.salonNo || !row.salonName) {
        this.$message.error('门店不能为空');
        return;
      }
      formData.append('sdtJson', JSON.stringify(row));
      const errAlertMsg = '文件上传失败';
      await fileTimelineDiagnose(formData)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert('文件上传失败: ' + res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.loadTimeline();
        })
        .catch(err => {
          console.error(err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.quanOpt.proposalUploading = false;
        });
    },
    loadDiagnoseData: async function (salon /* {salonId: '', salonNo: '', salonName: ''} */) {
      if (!salon || !salon.salonId) {
        return;
      }
      this.salon = Object.assign({}, salon);
      this.loadTimeline();
    },
    loadTimeline: async function () {
      if (this.isFetching) {
        return;
      }
      this.isFetching = true;
      this.form = Object.assign({}, EmptyTimeline);
      this.recordList.splice(0, this.recordList.length);
      const errAlertMsg = '查询时间线失败';
      await geTimelineDiagnose(this.salon.salonId)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret && ret.length) {
            this.recordList.push(...ret);
          }
        })
        .catch(err => {
          console.log('geTimelineDiagnose', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isFetching = false;
        });
    },
    handleSubmitForm: async function () {
      const row = this.form;
      row.id = null;
      row.salonId = this.salon.salonId;
      row.salonNo = this.salon.salonNo;
      row.salonName = this.salon.salonName;
      if (!row.salonId || !row.salonNo || !row.salonName) {
        MessageBox.alert('门店不能为空');
        return;
      }
      // diagnoseType 和 context 不能为空
      if (row.diagnoseType === undefined) {
        MessageBox.alert('请选择复盘主题');
        return;
      }
      // 删除 context 的前后空白字符
      row.context = row.context.trim();
      if (!row.context) {
        MessageBox.alert('请输入复盘内容');
        return;
      }

      this.isUpdating = true;
      const errAlertMsg = '保存时间线失败';
      saveTimelineDiagnose(row)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.loadTimeline();
        })
        .catch(err => {
          console.log('saveTimelineDiagnose', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isUpdating = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/scrollbar.scss';

.diagnose_time_line__ {
  width: 100%;
  padding: 0 0 0 0;
  display: flex;
  flex-direction: row-reverse;
  justify-content: flex-start;
  align-items: normal;
  background: none;

  .time_line {
    width: 100%;
    height: 100vh;
    background-color: beige;
    opacity: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-start;

    ul {
      padding-inline-start: 10px;
    }

    .time_line_history {
      width: 100%;
      height: 75vh;
      padding: 0 10px 0 0;
      display: block;
      overflow-x: hidden;
      overflow-y: scroll;
      background: linear-gradient(to bottom, #e5e8ed, #efeff1);
      border: 1px solid #e5e8ed;
      border-radius: 5px 5px 0 0;

      .time_line_body {
        min-height: 40px;
        margin: 0;
        padding: 0 5px 0 5px;
        position: relative;
        font-size: 0.096rem;
        line-height: 16px;
        color: #454545;

        .recorder__ {
          position: absolute;
          right: 10px;
          bottom: -5px;
          color: #666666;
          font-size: 10px;
        }
      }
    }

    .time_line_new {
      width: 100%;
      height: 25vh;
      padding: 0 0 5px 0;
      display: block;
      background: linear-gradient(to bottom, #efeff1, #e5e8ed);
      border: 1px solid #e5e8ed;
      border-radius: 0 0 5px 5px;

      .bottom_add {
        padding: 10px 16px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 5px;
      }
    }
  }
}
</style>
